package com.yys.gulimall.order.web;

import com.yys.gulimall.order.service.OrderService;
import com.yys.gulimall.order.vo.OrderConfirmVo;
import com.yys.gulimall.order.vo.OrderSubmitRespVo;
import com.yys.gulimall.order.vo.OrderSubmitVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.concurrent.ExecutionException;

/**
 * @author zq
 * @version 1.0
 * @date 2021/4/3 14:05
 */

@Controller
public class OrderWebController {

    @Autowired
    private OrderService orderService;

    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = orderService.confirmOrder();
        model.addAttribute("orderConfirm",orderConfirmVo);
        return "confirm";
    }

    /**
     *
     * 创建订单 验证令牌 锁库存
     * @param orderSubmitVo 下单vo
     * @return 去支付页,下单失败回到订单确认页
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo orderSubmitVo, Model model, RedirectAttributes redirectAttributes) {
        OrderSubmitRespVo orderSubmitRespVo = orderService.submitOrder(orderSubmitVo);
        if(orderSubmitRespVo.getCode() == 0) {
            //下单成功
            model.addAttribute("submitOrder",orderSubmitRespVo);
            return "pay";
        } else {
            String msg = "下单失败: ";
            switch (orderSubmitRespVo.getCode()) {
                case 1: msg += "订单信息过期,请重试";break;
                case 2: msg += "订单商品发生变化请确认后重新提交";break;
                case 3: msg += "库存不足";break;
                default:break;
            }
            redirectAttributes.addFlashAttribute("msg",msg);
            return "redirect:http://order.gulimall.com/toTrade";
        }
    }
}
